package com.zhangxin.aiInterview.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhangxin.aiInterview.common.BaseResponse;
import com.zhangxin.aiInterview.common.ResultUtils;
import com.zhangxin.aiInterview.manager.xfapi.http.WxGenerateExamQuestionApi;
import com.zhangxin.aiInterview.manager.xfapi.http.WxGenerateInterviewQuestionApi;
import com.zhangxin.aiInterview.model.dto.wx.WxGenerateExamQuestionRequest;
import com.zhangxin.aiInterview.model.dto.wx.WxGenerateInterviewQuestionRequest;
import com.zhangxin.aiInterview.model.dto.wx.WxLoginRequest;
import com.zhangxin.aiInterview.model.entity.Company;
import com.zhangxin.aiInterview.model.entity.Position;
import com.zhangxin.aiInterview.model.entity.TechField;
import com.zhangxin.aiInterview.model.vo.WxLoginUserVO;
import com.zhangxin.aiInterview.service.CompanyService;
import com.zhangxin.aiInterview.service.PositionService;
import com.zhangxin.aiInterview.service.TechFieldService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 微信小程序接口
 */
@RestController
@RequestMapping("/wx")
@Slf4j
public class WxController {

    @Resource
    private WxMaService wxMaService;
    @Resource
    private CompanyService companyService;
    @Resource
    private TechFieldService techFieldService;
    @Resource
    private PositionService positionService;
    @Resource
    private WxGenerateExamQuestionApi wxGenerateExamQuestionApi;
    @Resource
    private WxGenerateInterviewQuestionApi wxGenerateInterviewQuestionApi;

    /**
     * 微信小程序登录
     *
     * @param loginRequest 包含 code, avatarUrl, nickName 的请求体
     * @return 脱敏后的用户信息和登录凭证
     */
    @PostMapping("/login")
    public BaseResponse<WxLoginUserVO> login(@RequestBody WxLoginRequest loginRequest) {
        String code = loginRequest.getCode();
        String avatarUrl = loginRequest.getAvatarUrl();
        String nickName = loginRequest.getNickName();

        try {
            // 1. 使用前端传来的 code 调用微信接口，换取 openid 和 session_key
            WxMaJscode2SessionResult sessionInfo = wxMaService.jsCode2SessionInfo(code);
            String openid = sessionInfo.getOpenid();
            // session_key 是敏感信息，不应泄露，仅用于解密手机号等敏感操作

            log.info("用户登录成功，openid: {}, 昵称: {}, 头像临时地址: {}", openid, nickName, avatarUrl);

            // TODO: [核心业务逻辑] 在此处理您的用户系统逻辑
            // 1. 查询数据库中是否存在该 openid 的用户
            // User user = userService.getUserByOpenid(openid);
            // 2. 如果用户不存在，则创建新用户；如果存在，则更新昵称和头像
            // a. [重要] 下载微信临时头像到您的永久存储（如腾讯云COS、阿里云OSS）
            // 因为微信返回的 avatarUrl 是临时链接，有效期仅为24小时
            // String permanentAvatarUrl = cosService.upload(avatarUrl);
            // b. 创建或更新用户信息
            // if (user == null) {
            // user = userService.createUser(openid, nickName, permanentAvatarUrl);
            // } else {
            // user = userService.updateUser(user, nickName, permanentAvatarUrl);
            // }
            // 3. [重要] 生成您自己系统的登录凭证（如 JWT Token）
            // String token = jwtService.generateToken(user.getId());

            // 4. 返回自定义的登录用户信息给前端
            // 下面的VO仅为示例，实际应包含您业务需要的信息和Token
            WxLoginUserVO wxLoginUserVO = new WxLoginUserVO();
            wxLoginUserVO.setOpenid(openid); // 示例：返回openid
            wxLoginUserVO.setNickName(nickName); // 示例：返回前端传来的昵称
            wxLoginUserVO.setAvatarUrl(avatarUrl); // 示例：返回前端传来的临时头像地址，真实场景应返回永久地址
            // loginUserVO.setToken(token); // 真实场景应返回此Token

            return ResultUtils.success(wxLoginUserVO);
        } catch (Exception e) {
            log.error("微信小程序登录失败", e);
            throw new RuntimeException("小程序登录失败，请稍后重试");
        }
    }

    /**
     * 获取公司列表
     * @return
     */
    @GetMapping("/get/companyList")
    public BaseResponse<List<String>> getCompanyList() {
        // 使用 LambdaQueryWrapper 指定字段
        List<String> companyList = companyService.listObjs(
                new LambdaQueryWrapper<Company>().select(Company::getName),
                obj -> (String) obj  // 将 Object 转为 String
        );
        return ResultUtils.success(companyList);
    }
    /**
     * 获取技术领域列表
     */
    @GetMapping("/get/techFieldList")
    public BaseResponse<List<String>> getTechFieldList() {
        // 使用 LambdaQueryWrapper 指定字段
        List<String> techFieldList = techFieldService.listObjs(
                new LambdaQueryWrapper<TechField>().select(TechField::getName),
                obj -> (String) obj
        );
        return ResultUtils.success(techFieldList);
    }

    /**
     * 获取指定公司指定技术领域下的岗位列表
     * @param company
     * @param techField
     * @return
     */
    @GetMapping("/get/positionList")
    public BaseResponse<List<String>> getPositionList(@RequestParam("company") String company, @RequestParam("techField") String techField){
        List<Position> positionList = positionService.lambdaQuery()
                .eq(Position::getCompanyName, company)
                .eq(Position::getTechFieldName, techField)
                .list();
        List<String> list = positionList.stream()
                .map(Position::getName)
                .collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    /**
     * 生成笔试题
     * @param wxGenerateExamQuestionRequest
     * @return
     */
    @PostMapping("/generate/examQuestion")
    public BaseResponse<String> generateExamQuestion(@RequestBody WxGenerateExamQuestionRequest wxGenerateExamQuestionRequest){
        String company = wxGenerateExamQuestionRequest.getCompany();
        String techField = wxGenerateExamQuestionRequest.getTechField();
        String position = wxGenerateExamQuestionRequest.getPosition();
        String examQuestionJson = wxGenerateExamQuestionApi.generateExamQuestion(company, position);
        examQuestionJson = examQuestionJson.replaceAll("^```json\\s*|```\\s*", "");
        return ResultUtils.success(examQuestionJson);
    }

    /**
     * 生成面试题
     * @param wxGenerateInterviewQuestionRequest
     * @return
     */
    @PostMapping("/generate/interviewQuestion")
    public BaseResponse<String> generateInterviewQuestions(@RequestBody WxGenerateInterviewQuestionRequest wxGenerateInterviewQuestionRequest){
        String company = wxGenerateInterviewQuestionRequest.getCompany();
        String techField = wxGenerateInterviewQuestionRequest.getTechField();
        String position = wxGenerateInterviewQuestionRequest.getPosition();
        String examQuestionJson = wxGenerateInterviewQuestionApi.generateInterviewQuestion(company, position);
        examQuestionJson = examQuestionJson.replaceAll("^```json\\s*|```\\s*", "");
        return ResultUtils.success(examQuestionJson);
    }
}
